<template>
  <div class="c-pb32 c-bg-sgray">
    <div class="c-bg-white c-ph24 c-mb12">
      <div class="c-hh88 c-flex-row c-justify-sb c-aligni-center c-fs26 c-bd-b1">
        <div>头像</div>
        <div class="c-flex-row c-aligni-center">
          <div class="c-hh60 c-ww60 c-br30 c-text-hidden c-flex-row c-flex-center c-p c-mr10" @click="clickAddPic">
            <img class="c-w100 c-h c-object-fit-cover" :src="$addXossFilter(myInfo.avatar, require('@/assets/defult_head.png'))" alt="" v-if="avatar.length == 0">
            <img class="c-w100 c-h c-object-fit-cover" :src="$addXossFilter(avatar)" alt="" v-else>
            <input class="c-pa c-opacity0 c-p-t0 c-p-l0 c-ww60 c-hh60 c-br30 c-text-hidden" v-if="!isWeiXin" name="file" type="file" accept="image/*" @change="clickAddPic($event)" />
          </div>
          <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
        </div>
      </div>
      <div class="c-hh88 c-flex-row  c-aligni-center c-fs26 c-bd-b1" @click="editNickName(2)">
        <div>昵称</div>
        <div class="c-fc-gray c-flex-grow1 c-textAlign-r c-pr10">{{myInfo.nickname}}</div>
        <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
      </div>
      <div v-if="!isAndroidApp && !isiOSApp" class="c-hh88 c-flex-row  c-aligni-center c-fs26 c-bd-b1" @click="editRealName">
        <div class="c-ww360">真实姓名</div>
        <div class="c-fc-gray c-flex-grow1 c-textAlign-r c-pr10">{{myInfo.realName || ''}}</div>
        <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
      </div>
      <div class="c-hh88 c-flex-row c-justify-sb  c-aligni-center c-fs26 c-bd-b1">
        <div>性别</div>
        <div class="c-flex-row c-fc-gray c-flex-grow1 c-aligni-center c-justify-end">
          <popup-picker :themeColor="$getThemeColor()" @on-hide="saveGender" class="c-flex-grow1 c-pr10" :title="''" :data="sexData" v-model="sexValue" placeholder="请选择性别"></popup-picker>
          <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
        </div>
      </div>
      <div class="c-hh88 c-flex-row c-aligni-center c-fs26 c-bd-b1" @click="goBindPhone()">
        <div>手机号</div>
        <div class="c-fc-gray c-flex-grow1 c-textAlign-r c-pr10">{{isPhone ? myInfo.mobile : '请绑定手机号'}}</div>
        <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
      </div>
      <div v-if="hasAliPayAccountEntry" class="c-hh88 c-flex-row c-aligni-center c-fs26 c-bd-b1" @click="popAliAccountModal()">
        <div>支付宝账号</div>
        <div class="c-fc-gray c-flex-grow1 c-textAlign-r c-pr10">{{aliInfo.aliAccountEncry ? aliInfo.aliAccountEncry : '请绑定支付宝账号'}}</div>
        <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
      </div>
      <div class="c-bg-white c-hh88 c-flex-row c-justify-sb c-aligni-center c-fs26 c-bd-b1 c-p">
        <div>地区</div>
        <div v-if="isWeiXin && isOpenGetLocation" @click="getLocation" class="c-w90 c-h c-flex-row c-aligni-center c-justify-end">
          <div v-if="!(addrValue && addrValue.length)" class="c-fs26 c-lh34 c-fc-gray">
            <span>请点击定位</span>
          </div>
          <div v-else class="c-fs26 c-lh34 c-fc-gray">{{getAddressName(addrValue)}}</div>
          <span class="c-fs24 iconfont c-fc-sgray c-ml10">&#xe905;</span>
        </div>
        <div v-if="(!isWeiXin || !isOpenGetLocation) && addressData" class="c-flex-row c-fc-gray c-flex-grow1 c-justify-end">
          <x-address :themeColor="$getThemeColor()" v-model="addrValue" @on-hide="saveAddress" :title="''" :rawValue="true" :list="addressData" placeholder="请选择地址" :show.sync="showAddress"
            :disabled="(isPhone ? (addrValue != null && addrValue.length > 0 ? true : false) : false)" class="c-flex-grow1"></x-address>
        </div>
        <!-- <div class="errorTipText">{{isWeiXin && !isOpenGetLocation ? '请先把手机"设置-微信定位"开启' : ''}}</div> -->
      </div>
      <div class="c-bg-white c-hh88 c-flex-row c-justify-sb c-aligni-center c-fs26 c-bd-b1">
        <div>身份</div>
        <div class="c-fc-gray c-flex-grow1 c-textAlign-r c-pr10">{{custNameMap[myInfo.vipType]}}</div>
      </div>
      <div v-if="isFillUserInfo == 1" v-show="item.type != 2" class="c-bg-white c-hh88 c-flex-row c-aligni-center c-fs26" :class="index == customUserInfo.length - 1 ? '' : 'c-bd-b1'" v-for="(item,index) in customUserInfo" :key="index">
        <div class="c-ww360">{{item.title}}</div>
        <div class="c-fc-gray c-flex-grow1 c-textAlign-r c-pr10" @click="editInfo(index)">{{item.content}}</div>
        <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
      </div>
    </div>
    <div v-if="!isFaShou" class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-mb12" @click="updatePassword">
      <div>余额支付密码</div>
      <div class="c-fc-gray c-flex-grow1 c-textAlign-r"></div>
      <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
    </div>
    <!-- <div class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-mb12" @click="getAddressList">
      <div>我的收货地址</div>
      <div class="c-fc-gray c-flex-grow1 c-textAlign-r"></div>
      <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
    </div> -->
    <!-- 德福平台定制 请输入邀请码-->
    <div class="c-bg-white c-hh88 c-flex-row c-justify-sb c-aligni-center c-fs26 c-ph24 c-mb12" v-if="enableBindReferee==1 && Number(myInfo.reshowId) == 0" @click="editInviter">
      <div>请输入邀请码</div>
      <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
    </div>
    <div class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-mb12" v-else>
      <div>邀请人</div>
      <div v-if="myInfo.reshowId" class="c-fc-gray c-flex-grow1 c-flex-row c-justify-end" @click="editInviter">
        <div class="c-flex-row c-aligni-center">
          <div>
            <div>{{myInfo.refereeName}}</div>
            <div class="c-pt8">ID:{{myInfo.reshowId}}</div>
          </div>
          <span v-if="enableBindReferee==1" class="iconfont c-fs20 c-fc-sgray c-pl10">&#xe60e;</span>
        </div>
      </div>
      <div v-else class="c-fc-gray c-flex-grow1 c-textAlign-r">
        <div>无</div>
      </div>
    </div>
    <div class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-mb12" v-if="companyAuth.shareholderLevels > 0 && ((myInfo.sId && myInfo.sId.length > 0) || myInfo.sMobile)">
      <div>上级股东</div>
      <div class="c-fc-gray c-flex-grow1 c-flex-row c-justify-end">
        <div>
          <div>{{myInfo.sName || myInfo.sNickname}}</div>
          <div class="c-pt8">{{myInfo.sId && myInfo.sId.length > 0 ? "ID:" + myInfo.sId : "手机:" + myInfo.sMobile}}</div>
        </div>
      </div>
    </div>
    <div class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-bd-b1" v-if="myInfo.isStaff == 1">
      <div>我的分成</div>
      <div class="c-fc-gray c-flex-grow1 c-textAlign-r">{{myInfo.staffRatio}}%</div>
    </div>
    <div v-if="isAndroidApp" @click="linkToFeedback" class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-bd-b1">
      <div>意见反馈</div>
      <div class="c-fc-gray c-flex-grow1 c-textAlign-r"></div>
      <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
    </div>
    <div v-if="isAndroidApp || isiOSApp" @click="linkToPrivacyIndex" class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-bd-b1">
      <div>隐私设置</div>
      <div class="c-fc-gray c-flex-grow1 c-textAlign-r"></div>
      <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
    </div>
    <div v-if="isAndroidApp || isiOSApp" @click="linkToAboutUs" class="c-bg-white c-hh88 c-flex-row  c-aligni-center c-fs26 c-ph24 c-bd-b1">
      <div>关于我们</div>
      <div class="c-fc-gray c-flex-grow1 c-textAlign-r"></div>
      <i class="iconfont c-fs20 c-fc-sgray">&#xe60e;</i>
    </div>
    <section v-if="isAndroidApp || isiOSApp" @click="clickDelete" class="c-fs26 c-bg-white c-bd-b1 c-bd-t1 c-hh88 c-flex-row c-flex-center c-fc-xblack">注销账号</section>
    <section v-if="!isAndroidApp && !isiOSApp && companyAuth.version == 1 && !isNoWechatAndMobile && !isAPPH5Login" @click="clickUpdateInfo" class="c-fs26 c-bg-white c-bd-b1 c-bd-t1 c-hh88 c-flex-row c-flex-center c-fc-xblack">同步微信头像和昵称</section>
    <section v-if="isNoWechatAndMobile" @click="loginOut" class="c-fs26 c-bg-white c-bd-b1 c-bd-t1 c-hh88 c-flex-row c-flex-center c-flexw-wrap theme-fc c-mt12">退出登录</section>
    <section class="c-hh120 c-flex-row c-flex-center c-flexw-wrap theme-fc c-fs20" v-if="protocolInfo">
      <template v-if="isAndroidApp || isiOSApp">
        <span @click="linkToProtocol(protocolInfo.useProtocolUrl)">《用户服务协议》</span>
        <span class="c-ph40 theme-fc">|</span>
        <span @click="linkToProtocol(protocolInfo.privacyProtocolUrl)">《隐私政策》</span>
      </template>
      <template v-else>
        <div @click="clickProtocol(item)" v-for="(item, index) in protocolInfo" :key="index">
          <span>《{{item.name}}》</span><span class="c-ph40 theme-fc" v-if="index != (protocolInfo.length - 1)">|</span>
        </div>
      </template>
    </section>
    <!-- 修改自定义 -->
    <div v-if="customUserInfo && customUserInfo.length>0" v-show="show" class="c-pz1002 c-w100 c-h c-pf c-p-l0 c-p-t0 c-flex-row c-flex-center">
      <div class="c-translucent-balck50 c-text-hidden c-pz-1 c-w100 c-h c-pa c-p-l0 c-p-t0" @click="isShowRealNameDialog = false;" data-type='cancel'></div>
      <div class="c-ww540 c-bg-white c-flex-column c-pz1 c-br20">
        <div class="c-fs28 c-textAlign-c c-pt50 c-fw-b c-lh c-pb30">{{'修改'+customUserInfo[editIndex].title}}</div>
        <div class="c-ph30 ">
          <div class="c-w100 c-fs20 c-lh64 c-br10 c-bd1 c-mt10">
            <input type="text" id="comment" autofocus="autofocus" v-model="infoMsg" :placeholder="'请输入'+customUserInfo[editIndex].title" class="c-w100 c-bd0 c-text-indent20 c-h c-lh48 c-br10 c-fs26" />
          </div>
          <div class="c-hh50 c-lh50"></div>
        </div>
        <footer class="c-fs20 c-flex-row c-fs28 c-bd-t1">
          <div @click="show = false;infoMsg='';" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 c-fc-gray c-bd-r1">取消</div>
          <div @click="onConfirm" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 theme-fc">确定</div>
        </footer>
      </div>
    </div>
    <!-- 修改真实姓名 -->
    <div v-show="isShowRealNameDialog" class="c-pz1002 c-w100 c-h c-pf c-p-l0 c-p-t0 c-flex-row c-flex-center">
      <div class="c-translucent-balck50 c-text-hidden c-pz-1 c-w100 c-h c-pa c-p-l0 c-p-t0" @click="isShowRealNameDialog = false;" data-type='cancel'></div>
      <div class="c-ww540 c-bg-white c-flex-column c-pz1 c-br20">
        <div class="c-fs28 c-textAlign-c c-pt50 c-fw-b c-lh c-pb30">修改真实姓名</div>
        <div class="c-ph30 ">
          <div class="c-w100 c-fs20 c-lh64 c-br10 c-bd1 c-mt10">
            <input type="text" id="comment" autofocus="autofocus" maxlength="20" v-model="realNameInput" :placeholder="'请输入真实姓名'" class="c-w100 c-bd0 c-text-indent20 c-h c-lh48 c-br10 c-fs26" />
          </div>
          <div class="c-hh50 c-lh50"></div>
        </div>
        <footer class="c-fs20 c-flex-row c-fs28 c-bd-t1">
          <div @click="isShowRealNameDialog = false;" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 c-fc-gray c-bd-r1">取消</div>
          <div @click="setUserInfo(3, realNameInput)" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 theme-fc">确定</div>
        </footer>
      </div>
    </div>
    <!-- 修改邀请人 -->
    <div v-show="isShowInviterDialog" class="c-pz1002 c-w100 c-h c-pf c-p-l0 c-p-t0 c-flex-row c-flex-center">
      <div class="c-translucent-balck50 c-text-hidden c-pz-1 c-w100 c-h c-pa c-p-l0 c-p-t0" @click="onCancelInviter" data-type='cancel'></div>
      <div class="c-ww540 c-bg-white c-flex-column c-pz1 c-br20">
        <div class="c-fs28 c-textAlign-c c-pt50 c-fw-b c-lh c-pb30">请填写邀请您入驻店铺的邀请人ID号</div>
        <div class="c-ph30 ">
          <div class="c-w100 c-fs20 c-lh64 c-br10 c-bd1 c-mt10">
            <input type="text" autofocus="autofocus" v-model="inviterId" :placeholder="'请输入邀请人ID号'" class="c-w100 c-bd0 c-text-indent20 c-h c-lh48 c-br10 c-fs26" />
          </div>
          <div class="c-hh50 c-lh50 c-fs18 c-textAlign-l c-fc-red">注意:每个人只能填写—次，请务必核对正确</div>
        </div>
        <footer class="c-fs20 c-flex-row c-fs28 c-bd-t1">
          <div @click="onCancelInviter" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 c-fc-gray c-bd-r1">取消</div>
          <div @click="onConfirmInviter" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 theme-fc">确定</div>
        </footer>
      </div>
    </div>
    <!-- 修改昵称 -->
    <div v-show="showEditNickName" class="c-pz1002 c-w100 c-h c-pf c-p-l0 c-p-t0 c-flex-row c-flex-center">
      <div class="c-translucent-balck50 c-text-hidden c-pz-1 c-w100 c-h c-pa c-p-l0 c-p-t0" @click="showEditNickName = false;" data-type='cancel'></div>
      <div class="c-ww540 c-bg-white c-flex-column c-pz1 c-br20">
        <div class="c-fs28 c-textAlign-c c-pt50 c-fw-b c-lh c-pb30">修改昵称</div>
        <div class="c-ph30 ">
          <div class="c-w100 c-fs20 c-lh64 c-br10 c-bd1 c-mt10">
            <input type="text" ref="nickName" autofocus="autofocus" maxlength="16" :value="myInfo.nickname" :placeholder="'请输入新昵称'" class="c-w100 c-bd0 c-text-indent20 c-h c-lh48 c-br10 c-fs26" />
          </div>
          <div class="c-hh50 c-lh50 c-fs18 c-textAlign-l c-fc-red"></div>
        </div>
        <footer class="c-fs20 c-flex-row c-fs28 c-bd-t1">
          <div @click="showEditNickName = false;" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 c-fc-gray c-bd-r1">取消</div>
          <div @click="editNickName(3)" class="c-hh88 c-flex-row c-flex-center c-flex-grow1 c-w0 theme-fc">确定</div>
        </footer>
      </div>
    </div>
    <add-ali-account-com :showAddAliAccount="showAddAliAccount" :aliInfoDefault="aliInfo" @addAliPaySuccess="addAliPaySuccess" @closeDia="closeDia"></add-ali-account-com>
  </div>
</template>

<script>
import AddAliAccountCom from "@/components/templates/addAliAccountCom.vue";
import { XAddress, PopupPicker } from 'ckjrweb-mp-ui/src/components/index';
import { utilJs, wxUtilJs } from "@/utils/common.js";
import { loadBMap } from "@/utils/loadBMap.js"
import { ckjrRequest } from "@/utils/http.js";
let serverIdImgArr = []; //临时存放的上传图片searveID
let imgData = {};
export default {
  name: "InfoIndex",
  components: {
    AddAliAccountCom,
    PopupPicker,
    XAddress
  },
  props: [],
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      myInfo: {},
      showAddress: false,
      sexValue: ["男"],
      sexData: [["男", "女", '保密']],
      addrValue: [],
      addressData: '', // addressData,
      svShow: false,
      isPhone: false,
      customUserInfo: [],
      show: false,
      infoMsg: '',
      editIndex: -1,
      isAndroidApp: false,
      isiOSApp: false,
      isFillUserInfo: localStorage.getItem("isFillUserInfo"),
      isShowRealNameDialog: false, // 是否显示修改真实姓名弹窗
      isShowInviterDialog: false, // 是否显示修改邀请人弹窗
      realNameInput: '',
      inviterId: '', //邀请ID
      enableBindReferee: 0, // 0不能修改邀请人ID
      isWeiXin: true,
      avatar: '', // 上传图片
      showEditNickName: false,
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      isNoWechatAndMobile: false, // 判断是非微信浏览器并且是手机浏览器
      custNameMap: [],
      protocolInfo: null, // 通用协议
      isOpenGetLocation: true, // 是否开启定位
      isAPPH5Login: false, // 是否是定制app（目前就优匹）
      aliInfo: '',
      showAddAliAccount: false,
      hasAliPayAccountEntry: false, //启用平台商户的商家才有支付宝账号设置入口
      isFaShou: localStorage.getItem('isFaShou') == 1,
    };
  },
  computed: {
  },
  created() {
    utilJs.appShare(this);
  },
  methods: {
    closeDia() {
      this.showAddAliAccount = false;
    },
    popAliAccountModal() {
      this.showAddAliAccount = true;
    },
    addAliPaySuccess(aliData) {
      this.aliInfo.alipayAccount = aliData.alipayAccount;
      this.aliInfo.alipayUserName = aliData.alipayUserName;
      this.aliInfo.mobile = aliData.mobile;
      this.aliInfo.aliAccountEncry = this.aliInfo.alipayAccount.substr(0, 3) + '****' + this.aliInfo.alipayAccount.substr(-2, 2);
      this.showAddAliAccount = false;
    },
    getAddressName(addrValue) {
      let provinceStr = '', cityStr = '', areaStr = '';
      this.addressData && this.addressData.forEach(item => {
        if (item.value == addrValue[0]) {
          provinceStr = item.name
        }
        if (item.value == addrValue[1]) {
          cityStr = item.name
        }
        if (item.value == addrValue[2]) {
          areaStr = item.name
        }
      })
      return provinceStr + ' ' + cityStr + ' ' + areaStr
    },
    getAddId(list, id) {
      if (list && list.length == 1) {
        return list[0].value
      }
      let currentId = ''
      list.forEach((item) => {
        if (item.parent == id) {
          currentId = item.value
        }
      })
      return currentId
    },
    getAddressId(addComp) {
      let provinceId = '', cityIds = [], cityId = '', areaIds = [], areaId = ''
      this.addressData && this.addressData.forEach(item => {
        item.name = ['北京', '天津', '上海', '重庆'].includes(item.name) ? (item.name + '市') : item.name
        if (item.name == addComp.province && item.level == 1) {
          provinceId = item.value
        }
        if (item.name == addComp.city && item.level == 2) { // 防止市名重复
          cityIds.push(item)
        }
        if (item.name == addComp.district && item.level == 3) { // 防止区名重复
          areaIds.push(item)
        }
      })
      cityId = this.getAddId(cityIds, provinceId)
      areaId = this.getAddId(areaIds, cityId)
      this.addrValue = ['' + provinceId, '' + cityId, '' + areaId]
      // 如果定位获取到的数据不完整，就自动弹出选择框
      if (!(this.addrValue && this.addrValue.length == 3 && provinceId && cityId && areaId)) {
        this.addrValue = []
        this.isOpenGetLocation = false
        this.$nextTick(() => {
          this.showAddress = true
        })
        return
      }
      this.saveAddress(this.addrValue)
    },
    getLocation() {
      if (!this.isWeiXin) {
        return
      }
      let that = this;
      wxUtilJs.getLocation().then((res) => {
        that.getBdAddress(res.longitude, res.latitude);
        that.isOpenGetLocation = true;
      }, (failRes) => {
        that.isOpenGetLocation = false
        that.$nextTick(() => {
          that.showAddress = true
        })
        console.log('获取经纬度失败');
      });
    },
    getBdAddress(longitude, latitude) {
      /* eslint-disable */
      let that = this;
      that.$loading.hide();
      that.$loading.show({
        text: "定位中"
      });
      loadBMap().then(BMap => {
        let point = new BMap.Point(longitude, latitude)
        let gc = new BMap.Geocoder()
        gc.getLocation(point, function(rs){
          that.$loading.hide();
          const addComp = rs.addressComponents
          // 可以通过addComp对象获取到省、市、县、区、街道多少号等信息
          that.getAddressId(addComp)
        })
      })
    },
    loginOut() {
      this.$cjConfirm({
        title: '退出登录',
        message: '确定退出当前登录吗',
        onConfirm:() => {
          const ua = window.navigator.userAgent.toLowerCase()
          const isQywx = ua.match(/MicroMessenger/i) == 'micromessenger' && (ua.match(/wxwork/i) == "wxwork" || localStorage.getItem("wxAppEnvironment") == 'wxwork')
          utilJs.postMethod(global.apiurl + "common/delUserLoginKey", {}, res => {}); // 多端登录
          localStorage.clear();
          utilJs.setStoreId();
          if (isQywx) {
            utilJs.miniProgramGoTo("replace", "/pages/tabWebview/index")
          } else {
            this.$routerGo(this, "replace", {
              path: '/'
            })
          }
        }
      })
    },
    // 修改昵称
    editNickName(status) {
      if (status == 1) {
        this.showEditNickName = false;
      } else if (status == 2) {
        this.showEditNickName = true;
      } else if (status == 3) {
        let value = this.$refs.nickName.value;
        this.setUserInfo(2, value);
      }
    },
    // 保存头像/昵称/真实姓名
    setUserInfo(status, info) {
      let data = {};
      if (status == 1) {
        this.avatar = info;
        data.headimgurl = info;
      } else if (status == 2) {
        if (!/^[^\<>\s]*$/.test(info)) {
          this.$showCjToast({
            text: "输入内容不能包含特殊字符",
            type: 'warn',
            time: 2000
          });
          this.isShowRealNameDialog = false;
          return;
        } else if (info.trim().length == 0) {
          this.$showCjToast({
            text: "昵称不能为空",
            type: 'warn',
            time: 2000
          });
          this.isShowRealNameDialog = false;
          return;
        } else if (info.trim().length > 16) {
          this.$showCjToast({
            text: "昵称长度不得超过16个字符",
            type: 'warn',
            time: 2000
          });
          this.isShowRealNameDialog = false;
          return
        }
        data.nickname = info;
      } else if (status == 3) {
        if (info.length < 2 || info.length > 20) {
          this.$showCjToast({
            text: info.length < 2 ?"请输入真实姓名" : "不超过20个字符",
            type: 'warn',
            time: 2000
          });
          this.isShowRealNameDialog = false;
          return;
        }
        data.realName = info;
        if (this.isFillUserInfo == 1 && this.customUserInfo && this.customUserInfo.length > 0) {
          this.customUserInfo = this.customUserInfo.map(item => {
            if (item.type == 2) {
              item.content = info;
            }
            return item;
          })
        }
      }
      let that = this;
      utilJs.postMethod(global.apiurl + "members/mpInfo", data, res => {
        if (res) {
          that.$showCjToast({
            text: "修改成功",
            type: 'success',
            time: 1500,
          });
        }
        if (status == 2) {
          that.showEditNickName = false;
          that.$set(that.myInfo, 'nickname', info);
        } else if (status == 3) {
          that.isShowRealNameDialog = false;
          that.$set(that.myInfo, 'realName', info);
        }
      })
    },
    // 添加图片
    clickAddPic(event) {
      if (this.isWeiXin) {
        wxUtilJs.chooseImage({
          count: 1,
          sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"] // 可以指定来源是相册还是相机，默认二者都有
        }).then(localIds => {
          this.$loading.show({
            text: "上传中..."
          });
          serverIdImgArr = [];
          this.avatar = [];
          wxUtilJs.uploadImage({
            localId: localIds[0]
          }, true)
          .then(res => {
            serverIdImgArr.push(res);
            this.syncUploadPic(serverIdImgArr);
          }).catch(res => {
            this.$loading.hide();
            this.$showCjToast({
              text: "上传失败，请重试",
              type: "warn",
              time: 1500
            });
          });
        })
      } else {
        utilJs.imgUpload(event.target.files, imgData, 'info', res => {
          this.avatar = [];
          this.setUserInfo(1, res);
        }, fRes => {});
      }
    },
    //上传图片到服务器
    syncUploadPic(serverIdArr) {
      utilJs.postMethod(global.apiurl + "common/forms/wxUploadImg", {
        serverId: JSON.stringify(serverIdArr),
        mediaType: 2
      },
        res => {
          this.$loading.hide();
          this.setUserInfo(1, res[0]);
        },
        failRes => {
          this.$loading.hide();
        }
      );
    },
    editRealName() {
      this.isShowRealNameDialog = true;
    },
    editInviter() {
      //不允许修改邀请人ID
      if (this.enableBindReferee == 0) {
        return;
      }
      this.isShowInviterDialog = true;
    },
    onConfirmInviter() {
      if (!this.inviterId) {
        this.$showCjToast({
          text: "请输入正确邀请人ID",
          type: 'warn',
          time: 3000
        });
        return;
      }
      this.isShowInviterDialog = false;
      utilJs.postMethod(`${global.apiurl}Marketing/bindRefereeUser/${this.inviterId}`, {}, (res) => {
        this.$showCjToast({
          text: "修改成功",
          type: 'success',
          time: 3000
        })
        this.getInfo();
      })
    },
    onCancelInviter() {
      this.isShowInviterDialog = false;
      this.inviterId = "";
    },
    clickDelete() {
      this.$cjConfirm({
        title: '温馨提醒',
        message: '注销将删除所有数据，您确定要注销账号么？',
        confirmButtonText:'确定注销',
        onConfirm:() => {
          this.deleteAccount();
        }
      })
    },
    deleteAccount() {
      utilJs.postMethod(`${global.apiurl}mp/deleteAccount`, {}, (res) => {
        window.localStorage.clear();
        if (utilJs.isIOSApp()) {
          window.webkit.messageHandlers.iosWechatLoginOut.postMessage('loginOut');
        } else {
        utilJs.androidAppExit();
        }
      })
    },
    linkToProtocol(url) {
      if (!url) return
      window.location.href = url;
    },
    clickProtocol(item) {
      this.$routerGo(this, "push", { path: `/homePage/agent/protocolInfo`, query: { protocolId: item.protocolId } });
    },
    // 点击意见反馈
    linkToFeedback() {
      this.$routerGo(this, "push", { path: '/member/feedback/feedbackIndex' })
    },
    // 点击关于我们
    linkToAboutUs() {
      this.$routerGo(this, "push", { path: '/member/menberInfo/aboutUs' })
    },
    // 点击隐私设置
    linkToPrivacyIndex() {
      this.$routerGo(this, "push", { path: '/member/privacySetting/privacySettingIndex' })
    },
    // 修改支付密码
    updatePassword() {
      this.$routerGo(this, "push", { path: '/member/scholarship/updatePassword' });
    },
    // 跳转到收获地址
    getAddressList() {
      this.$routerGo(this, "push", { path: '/mall/shippingAddress/addressList' });
    },
    goBindPhone() {
      if (this.isPhone) {
        this.$routerGo(this, "push", {
          path: "/member/menberInfo/changeMobile"
        });
      } else {
        utilJs.goBindMobile();
      }
    },
    saveGender(closeType) {
      if (closeType) {
        let gender
        this.sexValue == '男' ? gender = 1 : (this.sexValue == '女' ? gender = 2 : gender = -1)
        let $this = this
        utilJs.postMethod(global.apiurl + 'members/mpInfo', {
          gender: gender
        }, function (res) {
          if (res) {
            $this.$showCjToast({
              text: "修改成功",
              type: 'success',
              time: 3000
            });
          }
        })
      }
    },
    saveAddress(closeType) {
      if (closeType) {
        if (this.addrValue.length == 0) {
          this.$showCjToast({
            text: "请选择地址",
            type: 'warn',
            time: 3000
          });
        }
        let provinceId = this.addrValue[0]
        let cityId = this.addrValue[1]
        let areaId = this.addrValue[2]
        utilJs.postMethod(global.apiurl + 'members/mpInfo', {
          provinceId: provinceId,
          cityId: cityId,
          areaId: areaId
        }, (res) => {
          if (res) {
            this.$showCjToast({
              text: this.isWeiXin ? "重新定位成功" : "修改成功",
              type: 'success',
              time: 3000
            });
          }
        })
      }
    },
    getInfo() {
      //获取个人信息
      var $this = this;
      this.memberId = localStorage.getItem('memberId');
      utilJs.getMethod(global.apiurl + 'members', function (res) {
        $this.isPhone = localStorage.getItem("uMobile");
        $this.myInfo = res;
        $this.realNameInput = res.realName;
        $this.customUserInfo = res.customUserInfo || [];
        $this.enableBindReferee = res.enableBindReferee;
        if (!$this.myInfo.hasOwnProperty('alipayAccount')) {
          $this.hasAliPayAccountEntry = false;
        } else {
          $this.hasAliPayAccountEntry = true;
          $this.aliInfo = {
            'alipayAccount': $this.myInfo.alipayAccount,
            'alipayUserName': $this.myInfo.alipayUserName,
            'mobile': $this.myInfo.mobile,
            'aliAccountEncry': $this.myInfo.alipayAccount ? ($this.myInfo.alipayAccount.substr(0, 3) + '****' + $this.myInfo.alipayAccount.substr(-2, 2)) : ''
          }
        }
        res.gender == 1 ? $this.sexValue = ['男'] : (res.gender == 2 ? $this.sexValue = ['女'] : $this.sexValue = ['保密']);
        if (res.provinceId != null && res.cityId != null) {
          $this.addrValue = ['' + res.provinceId, '' + res.cityId, '' + res.areaId]
        }

        let timeEnd = 0;
        let vEnd = 0;
        let sEnd = 0;
        if (res.vipEndTime != null && res.vipEndTime != '') {
          let stringTime = res.vipEndTime.replace(/-/g, '\/');
          let date = new Date(stringTime);
          let timestamp = Date.parse(date);
          timestamp = timestamp / 1000;
          vEnd = timestamp;
        } else if (res.svipEndTime != null && res.svipEndTime != '') {
          let stringTime = res.svipEndTime.replace(/-/g, '\/');
          let timestamp = Date.parse(new Date(stringTime));
          timestamp = timestamp / 1000;
          sEnd = timestamp;
        }
        timeEnd = vEnd >= sEnd ? vEnd : sEnd;
        let nowTime = new Date().getTime();
        nowTime = nowTime / 1000;
        $this.svShow = nowTime > timeEnd ? true : (res.vipType == 1);
      })
    },
    //分享
    wechatShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.wechatConfig(shareUrl, "个人信息", "", "", function () { }, true);
    },
    //手机端分享
    appShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("个人信息", "", shareUrl, "");
    },
    onConfirm: function () {
      if (this.customUserInfo[this.editIndex].type == 3 && this.infoMsg != '' && this.infoMsg.length > 20) {
        this.$showCjToast({
          text: '不能超过20字符！',
          type: 'warn'
        });
      } else if (this.infoMsg != '' && this.infoMsg.length > 0) {
        if (utilJs.getChineseStrLength(this.infoMsg) > 100) {
          this.$showCjToast({
            text: '不能超过100字符！',
            type: 'warn'
          });
          return;
        }
        this.customUserInfo[this.editIndex].content = this.infoMsg;
        let data = {
          customUserInfo: this.customUserInfo
        };
        let $this = this;
        utilJs.postMethod(global.apiurl + 'members/mpInfo', data, function (res) {
          $this.infoMsg = '';
          $this.$showCjToast({
            text: '修改成功',
            type: 'success'
          });
        });
        this.show = false;
      } else {
        this.$showCjToast({
          text: '请输入内容',
          type: 'warn'
        });
      }
    },
    editInfo(eIndex) {
      this.editIndex = eIndex;
      this.infoMsg = this.customUserInfo[this.editIndex].content;
      this.show = true;
    },
    clickUpdateInfo() {
      // 先返回就得同步再走手动授权得流程
      // utilJs.getMethod(`${global.apiurl}mp/getWxUserInfo`, (res) => {
      //   if (res.isFollowedMp == -1) {
      //     this.$store.commit('updateShowAttentionQr', true);
      //   } else if (res.isFollowedMp == 1) {
      //     window.location.reload(true);
      //   }
      // });
      let companyId = localStorage.getItem('companyId');
      localStorage.removeItem(`${companyId}|token`);
      localStorage.removeItem(`${companyId}`);
      localStorage.removeItem("companyId");
      localStorage.removeItem("userId");
      localStorage.removeItem("token");
      // window.location.reload(true);
      // localStorage.clear();
      let bu = '/member/menberInfo/infoIndex';
      localStorage.setItem("beforeLoginUrl", bu);
      localStorage.setItem("forceUpdateUw", 1);
      const requestUrl = `${global.apiurl}mp/initAuth?c=${companyId}&forceUpdateUw=1&backUrl=${encodeURIComponent(window.location.href.split("#/")[0] + '#' + bu)}${this.$isWxApp() ?'&chl=xcx' : ''}${sessionStorage.getItem('promotedAccountId') ? ('&promotedAccountId=' + sessionStorage.getItem('promotedAccountId')) : ''}`;
      ckjrRequest({url:requestUrl}).then(response => {
        if (response.data) {
          window.location.href = response.data + '&time=' + Date.parse(new Date());
        }
      }).catch(function (error) { });
    },
    getAppUseAndPrivacyProtocols() {
      utilJs.getMethod(`${global.apiurl}app/getAppUseAndPrivacyProtocols`, (res) => {
        this.isCheckAgreement = false;
        this.protocolInfo = res || null;
      });
    },
    getGeneralProtocol() {
      utilJs.getMethod(`${global.apiurl}protocols/getGeneralProtocol`, (res) => {
        this.protocolInfo = res.protocol && res.protocol.length > 0 ? res.protocol : null;
      });
    }
  },
  activated() {
    this.avatar = '';
    this.myInfo = {};
    this.isAndroidApp = utilJs.isAndroidApp();
    this.isiOSApp = utilJs.isIOSAppALL();
    this.svShow = false;
    this.editIndex = 0;
    this.show = false;
    this.isShowRealNameDialog = false;
    this.isShowInviterDialog = false;
    this.inviterId = '';
    this.realNameInput = '';
    this.enableBindReferee = 0;
    this.isPhone = localStorage.getItem("uMobile");
    const ua = window.navigator.userAgent.toLowerCase()
    // 企微环境，不管是手机端还是电脑端的套壳小程序（h5在企微环境登录不了，不会到这个页面）都是都是走手机号登录
    const isQywx = ua.match(/MicroMessenger/i) == 'micromessenger' && (ua.match(/wxwork/i) == "wxwork" || localStorage.getItem("wxAppEnvironment") == 'wxwork')
    this.isNoWechatAndMobile = (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) != 'micromessenger' && !!navigator.userAgent.match(/AppleWebKit.*Mobile.*/)) || isQywx;
    let u = navigator.userAgent;
    this.isAPPH5Login = u.indexOf('APPH5Login') > -1; //  APPH5Login:走h5支付，又要分享的时候（目前只有优匹定制采用）
    this.custNameMap = utilJs.getCustNameMap();
    this.aliInfo = '';
    this.showAddAliAccount = false;
    this.hasAliPayAccountEntry = false;
    setDocumentTitle("个人信息");// eslint-disable-line
    utilJs.getMethod(`${global.apiurl}common/getAreaListForAgent`, res => {
      this.addressData = res.data;
      this.getInfo();
    }, failRes => {
    });
    this.wechatShare();
    this.isWeiXin = utilJs.isWeiXin();
    serverIdImgArr = []; //上传图片的serverID
    //获取阿里云签名，除了微信浏览器以外
    if (!utilJs.isWeiXin()) {
      utilJs.getAliSign(`${global.apiurl}imageSign`, res => {
        imgData = res;
      });
    }
    if (this.isAndroidApp || this.isiOSApp) {
      this.getAppUseAndPrivacyProtocols();
    } else {
      this.getGeneralProtocol();
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.c-text-indent20{text-indent: 0.5rem;}
.errorTipText {
  font-weight: 400;
  font-size: 0.45rem;
  color: #ff300c;
  line-height: 0.65rem;
  position: absolute;
  right: 0;
  bottom: 0;
}
</style>
